package com.hue.gulimail.gulimailorder.web;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.hue.common.utils.R;
import com.hue.gulimail.gulimailorder.pay.AlipayTemplate;
import com.hue.gulimail.gulimailorder.pay.PayVo;
import com.hue.gulimail.gulimailorder.service.OrderService;
import com.hue.gulimail.gulimailorder.vo.OrderConfirmVo;
import com.hue.gulimail.gulimailorder.vo.OrderResVo;
import com.hue.gulimail.gulimailorder.vo.OrderSubmitVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.concurrent.ExecutionException;

/**
 * @Author: 姚凤桥
 * @Date: 2021/12/24 15:40
 * @Description:
 */
@Controller
public class OrderWebController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private AlipayTemplate alipayTemplate;

    /**
     * 订单结算,跳转到订单确认页
     *
     * @return
     */
    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = orderService.getOrderConfirmVo();

        model.addAttribute("order", orderConfirmVo);

        return "confirm";
    }

    /**
     * 提交订单
     *
     * @return
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo orderSubmitVo, Model model, RedirectAttributes redirectAttributes) throws ExecutionException, InterruptedException {
        try {
            //下单:验证令牌-->创建订单-->验证价格-->锁库存...
            OrderResVo orderResVo = orderService.submitOrder(orderSubmitVo);

            if (orderResVo.getCode() == 0) {
                model.addAttribute("order", orderResVo.getOrder());
                return "pay";
            }
        } catch (Exception e) {
            //下单失败
            redirectAttributes.addFlashAttribute("msg", "库存不足了!");
        }

        return "redirect:http://order.gulimail.com/toTrade";
    }

    /**
     * 支付流程：使用支付宝支付时先跳转到支付宝的支付页面，支付成功后跳转到用户的订单详细页
     *
     * @param orderSn
     * @return
     * @throws AlipayApiException
     */
    @ResponseBody
    //返回一个html文本
    @GetMapping(value = "/payOrder", produces = "text/html")
    public String payOrder(@RequestParam("orderSn") String orderSn) throws AlipayApiException {
        PayVo payVo = orderService.getPayVoByOrderSn(orderSn);

        //调用支付方法时会返回支付宝的支付页面
        String payPage = alipayTemplate.pay(payVo);

        return payPage;
    }
}
